package com.aaa.dao.impl;

import com.aaa.dao.CinemaDao;
import com.aaa.entity.Cinema;
import com.aaa.entity.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class CinemaDaoImpl implements CinemaDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private RowMapper<Cinema> rowMapper = new RowMapper<Cinema>() {
        public Cinema mapRow(ResultSet resultSet, int i) throws SQLException {
            Cinema cinema = new Cinema();
            cinema.setCid(resultSet.getLong("cid"));
            cinema.setName(resultSet.getString("name"));
            cinema.setAddress(resultSet.getString("address"));
            cinema.setPhone(resultSet.getString("phone"));
            Object tid = resultSet.getInt("tid");
            if(tid!=null){
                City city = new City();
                city.setTid(resultSet.getLong("tid"));
                city.setTname(resultSet.getString("tname"));
                cinema.setCity(city);
            }
            return cinema;
        }
    };

    public List<Cinema> listPage(String keyword, Integer offset, Integer limit){
        String sql = "select c.cid,c.name,c.address,c.phone,t.tid,t.tname from cinema c inner join city t on c.tid = t.tid where c.name like ? order by c.cid desc limit ?,? ";
        List<Cinema> result = this.jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%", offset, limit);
        return result;
    }

    public Integer count(String keyword){
        String sql = "select count(cid) as c from cinema where name like ?";
        Integer result = this.jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        }, "%" + keyword + "%");
        return result;
    }

    public Integer save(Cinema cinema){
        String sql = "insert into cinema(name,address,phone,tid) values(?,?,?,?)";
        int count = this.jdbcTemplate.update(sql, cinema.getName(), cinema.getAddress(), cinema.getPhone(), cinema.getCity().getTid());
        return count;
    }

    public Integer update(Cinema cinema){
        String sql = "update cinema set name = ?,address = ?,phone = ?,tid = ? where cid = ?";
        int count = this.jdbcTemplate.update(sql, cinema.getName(), cinema.getAddress(), cinema.getPhone(),cinema.getCity().getTid(),cinema.getCid());
        return count;
    }

    public Integer delete(Long cid){
        String sql = "delete from cinema where cid = ?";
        int count = this.jdbcTemplate.update(sql, cid);
        return count;
    }
}
